package com.xhsj.user.lsm.web;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.xhsj.user.hr.system.mapper.TbGlobalUserMapper;
import com.xhsj.user.hr.system.service.TbGlobalUserService;
import com.xhsj.user.lsm.entity.TbBadgesProcessHiTask;
import com.xhsj.user.lsm.entity.TbBadgesUseApply;
import com.xhsj.user.lsm.mapper.TbBadgesUseApplyMapper;
import com.xhsj.user.lsm.model.MyBadgesUseApplyModel;
import com.xhsj.user.lsm.service.TbBadgesManagerService;
import com.xhsj.user.lsm.service.TbBadgesProcessHiTaskService;
import com.xhsj.user.lsm.service.TbBadgesProcessOpinionService;
import com.xhsj.user.lsm.service.TbBadgesUseApplyService;
import com.xhsj.user.utils.DateUtils;
import com.xhsj.user.utils.IdGen;
import com.xhsj.user.utils.Message;
import com.xhsj.user.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Pattern;


/**
 * <p>
 * 证章使用申请 前端控制器
 * </p>
 *
 * @author suxiaolin
 * @since 2020-03-16
 */
@Slf4j
@Api(tags = "证章使用申请")
@RestController
@RequestMapping("/process/tbBadgesUseApply")
public class TbBadgesUseApplyController {

	@Autowired
    public TbBadgesUseApplyService service;

	@Autowired
	private TbBadgesUseApplyMapper tbBadgesUseApplyMapper;


	@Autowired
	private TbGlobalUserService tbGlobalUserService;

    @Autowired
	TbBadgesProcessOpinionService tbBadgesProcessOpinionService;

	@Autowired
	public TbBadgesManagerService tbBadgesManagerService;

	@Autowired
	private TbBadgesProcessHiTaskService tbBadgesProcessHiTaskService;

	@Autowired
	private TbGlobalUserMapper userMapper;

	//角色名称 综合管理部
    @Value("${rolekeyname.integratedManager}")
    private String integratedManager;

    //角色名称 总经理
    @Value("${rolekeyname.generalManager}")
    private String generalManager;


	@ApiOperation(value = "证章使用申请,保存/修改", notes = "证章使用申请,保存和修改方法")
	@RequestMapping(value = "/save", method = RequestMethod.POST)
    //@PreAuthorize("hasAuthority('tb:badges:use:apply:edit')")
	public Message save(@RequestBody TbBadgesUseApply data){
    	try {
    		data.setAcType(0);
			data.setSignificanceIdentify(2);
			data.setUseSource(1);
    		service.startProcess(data);
        	return Message.success("保存成功");
		} catch (Exception e) {
			log.error("保存失败:{}",e);
        	return Message.error(e.getMessage());
		}

	}

	@GetMapping("/genUUid")
	public String genUUid(){
        String uuid = IdGen.uuid();
        return uuid;
    }


	@ApiOperation(value = "撤回申请", notes = "撤回申请")
	@RequestMapping(value = "/cancle", method = RequestMethod.GET)
	public Message cancle(@RequestParam("id") String id) {

		try {
			String nodeId = "5e8d804d54b2485391d10231fdddf4cc";
			QueryWrapper<TbBadgesProcessHiTask> queryWrapper = new QueryWrapper<>();
			queryWrapper.eq("node_id",nodeId);
			queryWrapper.eq("data_id",id);
			queryWrapper.eq("status",2);// 未审核
			Map<String, Object> map = tbBadgesProcessHiTaskService.getMap(queryWrapper);
			if (map !=null) {
				service.cancle(id);
				return Message.success("撤回成功");
			}else{
				return Message.error("目前不能撤回,请联系相关审核人员退回");
			}
		} catch (Exception e) {
			e.printStackTrace();
			return Message.error("删除数据异常");
		}
	}

	@ApiOperation(value = "行政助理处理操作", notes = "行政助理处理操作")
	@RequestMapping(value = "/handle", method = RequestMethod.GET)
	public Message handle(@RequestParam("id") String id) {

		try {

			TbBadgesUseApply tbBadgesUseApply = new TbBadgesUseApply();
			tbBadgesUseApply.setId(id);
			tbBadgesUseApply.setAcType(1);
			service.updateById(tbBadgesUseApply);
			return Message.success("处理成功");
		} catch (Exception e) {
			log.error("处理异常,{}",e);
			return Message.error("处理异常");
		}
	}


	@ApiImplicitParam(name = "data", value = "{\n" +
			"\"page\":1,\n" +
			"\"size\":10,\n" +
			"\"userId\":\"277\",\n" +
			"\"status\":0\n" +
			"}", required = true, dataType = "data")
	@ApiOperation(value = "主管审核", notes = "主管审核")
	@RequestMapping(value = "/directorAudit", method = RequestMethod.POST)
	//@PreAuthorize("hasAuthority('tb:badges:use:apply:edit')")
	public Message directorAudit(@RequestBody Map<String,Object> data){
		try {
            if(StringUtils.toInteger(data.get("status"))==0) {
                //根据角色名查找角色
                List<String> roleListByRoleName = tbGlobalUserService.getRoleListByRoleName(integratedManager);
				if (roleListByRoleName ==null || roleListByRoleName.size() == 0) {
					return Message.error(1,"下一节点审核角色不存在,请联系管理员添加相关人员");
				}
				// 检查角色下是否有用户
				tbGlobalUserService.checkRoleUserId(integratedManager,"综合管理部负责人");
                data.put("roleIds",roleListByRoleName);
            }
            service.execProcess(data);
			return Message.success("保存成功");
		} catch (Exception e) {
			log.error("保存失败:{}",e);
			// TODO: handle exception
			return Message.error(e.getMessage());

		}
	}


    @ApiImplicitParam(name = "data", value = " \n" +
            "{ \n" +
            "\"createBy\":\"304\",\n" +
            "\"dataId\":\"7ff021786f89409f8bf53623d69d9cb1\",\n" +
            "\"status\":2,\n" +
            "\"nodeId\":\"71a072f0acf646a4bea56ebb9958246b\"\n" +
            "}\n" +
            " ", required = true, dataType = "data")
    @ApiOperation(value = "综合管理部审核", notes = "综合管理部审核")
    @RequestMapping(value = "/generalManagementAudit", method = RequestMethod.POST)
    //@PreAuthorize("hasAuthority('tb:badges:use:apply:edit')")
    public Message generalManagementAudit(@RequestBody Map<String,Object> data){
        try {
//            if(StringUtils.toInteger(data.get("status"))==0 && StringUtils.toInteger(data.get("significanceIdentify"))==2) {
//                //根据角色名查找角色
//                List<String> roleListByRoleName = tbGlobalUserService.getRoleListByRoleName(roleNameTwo);
//				if (roleListByRoleName ==null || roleListByRoleName.size() == 0) {
//					return Message.error(1,"下一节点审核角色不存在,请联系管理员添加相关人员");
//				}
//                data.put("roleIds", roleListByRoleName);
//            }else if(StringUtils.toInteger(data.get("status"))==0){
//                data.put("userId", Arrays.asList(String.valueOf(data.get("proposerId")).split(",")));
//            }

			if (StringUtils.toInteger(data.get("status"))==0) {
				if (StringUtils.toInteger(data.get("significanceIdentify"))==2) {
					//根据角色名查找角色
					List<String> roleListByRoleName = tbGlobalUserService.getRoleListByRoleName(generalManager);
					if (roleListByRoleName ==null || roleListByRoleName.size() == 0) {
						return Message.error(1,"下一节点审核角色不存在,请联系管理员添加相关人员");
					}
                    // 检查角色下是否有用户
					tbGlobalUserService.checkRoleUserId(generalManager,"总经理");
					data.put("status",2);
					data.put("roleIds", roleListByRoleName);
				}else{
					// 检查用户是否存在
					tbGlobalUserService.checkUserId(data.get("proposerId"));
					data.put("userId", Arrays.asList(String.valueOf(data.get("proposerId")).split(",")));
				}
			}
           service.execProcess(data);
			return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}",e);
            // TODO: handle exception
			return Message.error(e.getMessage());
        }
    }


    @ApiImplicitParam(name = "data", value = " \n" +
            "{ \n" +
            "\"createBy\":\"304\",\n" +
            "\"dataId\":\"7ff021786f89409f8bf53623d69d9cb1\",\n" +
            "\"status\":2,\n" +
            "\"nodeId\":\"71a072f0acf646a4bea56ebb9958246b\"\n" +
            "}\n" +
            " ", required = true, dataType = "data")
    @ApiOperation(value = "总经理审核", notes = "总经理审核")
    @RequestMapping(value = "/managerAudit", method = RequestMethod.POST)
    //@PreAuthorize("hasAuthority('tb:badges:use:apply:edit')")
    public Message managerAudit(@RequestBody Map<String,Object> data){
        try {
			if(StringUtils.toInteger(data.get("status"))==0) {
				// 检查用户是否存在
				 tbGlobalUserService.checkUserId(data.get("proposerId"));
            	 data.put("userId", Arrays.asList(String.valueOf(data.get("proposerId")).split(",")));
			}
            service.execProcess(data);
			return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}",e);
            // TODO: handle exception
			return Message.error(e.getMessage());
        }
    }

    @ApiImplicitParam(name = "data", value = " \n" +
            "{ \n" +
            "\"createBy\":\"304\",\n" +
            "\"dataId\":\"7ff021786f89409f8bf53623d69d9cb1\",\n" +
            "\"status\":2,\n" +
            "\"nodeId\":\"71a072f0acf646a4bea56ebb9958246b\"\n" +
            "}\n" +
            " ", required = true, dataType = "data")
    @ApiOperation(value = "申请人填写文件登记", notes = "申请人填写文件登记")
    @RequestMapping(value = "/applicantAudit", method = RequestMethod.POST)
    //@PreAuthorize("hasAuthority('tb:badges:use:apply:edit')")
    public Message applicantAudit(@RequestBody Map<String,Object> data){
		if(StringUtils.toInteger(data.get("status"))==0 || StringUtils.toInteger(data.get("status"))==2) {
			// 检查用户是否存在
			try {
				tbGlobalUserService.checkUserId(data.get("proposerId"));
				data.put("userId", Arrays.asList(String.valueOf(data.get("proposerId")).split(",")));
			} catch (Exception e) {
				return Message.error(e.getMessage());
			}
		  }
        try {
            String badgesManagerId = String.valueOf(data.get("badgesManagerId"));
            boolean b = service.execProcess(data);
            if(b){
                //修改证章管理使用状态 0 空闲 1 使用
				boolean i = tbBadgesManagerService.updateBadgesManagerUseStatus(1, badgesManagerId);
                if(!i){
                    log.error("修改证章管理使用状态失败");
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//关键
                    throw new Exception("修改证章管理使用状态失败");
                }
            }else{
                log.error("完结失败");
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//关键
                throw new Exception("完结失败");
            }
			return Message.success("保存成功");
        } catch (Exception e) {
            log.error("保存失败:{}",e);
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//关键
			return Message.error(e.getMessage());
        }
    }

	@ApiImplicitParam(name = "data", value = " \n" +
			"{ \n" +
			"\"createBy\":\"304\",\n" +
			"\"dataId\":\"7ff021786f89409f8bf53623d69d9cb1\",\n" +
			"\"status\":2,\n" +
			"\"nodeId\":\"71a072f0acf646a4bea56ebb9958246b\"\n" +
			"}\n" +
			" ", required = true, dataType = "data")
	@ApiOperation(value = "完结", notes = "完结")
	@RequestMapping(value = "/endAudit", method = RequestMethod.POST)
	public Message endAudit(@RequestBody Map<String,Object> data){
		try {
			String badgesManagerId = String.valueOf(data.get("badgesManagerId"));
            boolean b = service.execProcess(data);
			if(b){
               //修改证章管理使用状态 0 空闲 1 使用
				boolean i = tbBadgesManagerService.updateBadgesManagerUseStatus(0, badgesManagerId);
                if(!i){
                    log.error("修改证章管理使用状态失败");
					TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//关键
                    throw new Exception("修改证章管理使用状态失败");
                }
			}else{
                log.error("完结失败");
				TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//关键
                throw new Exception("完结失败");
            }
			return Message.success("保存成功");
		} catch (Exception e) {
			log.error("保存失败:{}",e);
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();//关键
			return Message.error("保存失败");
		}
	}

	@ApiOperation(value = "获取使用列表", notes = "获取使用列表")
	@RequestMapping(value = "/getUseList", method = RequestMethod.POST)
	public Message getUseList(@RequestBody Map<String,Object> data) {

		try {
			int currentPage=1;
			if (!Objects.isNull(data.get("page"))) {
				currentPage=(Integer) data.get("page");
			}
			int pageSize=20;
			if (!Objects.isNull(data.get("size"))) {
				pageSize=(Integer) data.get("size");
			}

			Page<TbBadgesUseApply> page = new Page(currentPage,pageSize);
			QueryWrapper<TbBadgesUseApply> queryWrapper = new QueryWrapper<>();

			if (!Objects.isNull(data.get("name"))) {
				queryWrapper.like("name",data.get("name").toString());
			}

			if (!Objects.isNull(data.get("applyReason"))) {
				queryWrapper.like("apply_reason",data.get("applyReason").toString());
			}
			queryWrapper.in("node_name","填写文件登记表","使用中");

			IPage<Map<String,Object>> selectPage = service.getUseList(data);


//			IPage<TbBadgesUseApply> selectPage = service.selectPage(page, queryWrapper);
//			for (TbBadgesUseApply record : selectPage.getRecords()) {
//				String type = record.getType();
//				List<String> list = Arrays.asList(type.split(","));
//				record.setTypes(list);
//
//			}
			return Message.success("查询成功",selectPage.getRecords(),selectPage.getTotal());
		} catch (Exception e) {
			e.printStackTrace();
			return Message.error("查询失败");
		}

	}


	@ApiOperation(value = "证章使用申请删除", notes = "通过id删除证章使用申请信息。")
	@RequestMapping(value = "/delete", method = RequestMethod.GET)
    //@PreAuthorize("hasAuthority('tb:badges:use:apply:delete')")
	public Message delete(@RequestParam(value="id") String id) {
		try {
			service.removeById(id);
			return Message.success("删除成功");
		} catch (Exception e) {
			e.printStackTrace();
			// TODO: handle exception
			return Message.error("删除失败");
		}

	}

//	@ApiOperation(value = "批量删除", notes = "批量删除。")
//	@RequestMapping(value = "/batchDelete", method = RequestMethod.POST)
//	public Result batchDelete(@RequestBody List<String> list) {
//		try {
//			service.removeByIds(list);
//			return new Result<>(Result.CODE_SUCCESS,"删除成功");
//		} catch (Exception e) {
//			e.printStackTrace();
//			// TODO: handle exception
//			return new Result<>(Result.CODE_FAILED,"删除失败");
//		}
//    }

	@ApiOperation(value = "分页查询证章使用申请list", notes = "带参数查询,{\"page\": 1,\"size\": 5,......}。支持模糊查询")
	@RequestMapping(value="/findList",method = RequestMethod.POST)
    //@PreAuthorize("hasAuthority('tb:badges:use:apply:view')")
	public Message findList(@RequestBody Map<String,Object> data) {
        try {
        	if(StringUtils.isBlank(data.get("userId"))){
				return Message.error("当前用户id不能为空");
			}
        	IPage<MyBadgesUseApplyModel> selectPage = service.selectPage(data);

			for (MyBadgesUseApplyModel record : selectPage.getRecords()) {
				String type = record.getType();
				if (StringUtils.isNotBlank(type)) {
					List<String> list = Arrays.asList(type.split(","));
					record.setTypes(list);
				}
				if(StringUtils.isNotBlank(record.getUserId())){
                   String fullName = tbGlobalUserService.getFullNameByUserId(record.getUserId());
                    record.setHandler(fullName);

				}else if(StringUtils.isNotBlank(record.getRoleId())){
                    String fullName = tbGlobalUserService.getFullNameByRoleId(record.getRoleId());
                    record.setHandler(fullName);
				}
			}

			return Message.success("",selectPage.getRecords(),selectPage.getTotal());
        } catch (Exception e) {
        	e.printStackTrace();
        	return Message.error("查询异常");
        }
	}

	/**
	 *
	 * @author 苏小林
	 * @date 2020/7/1 16:25
	 * @param: data
	 * @return: com.xhsj.badges.utils.Message
	 */
	@ApiOperation(value = "查询证章模块个人转入转出列表", notes = "查询证章模块个人转入转出列表")
	@RequestMapping(value="/findApplyList",method = RequestMethod.POST)
	public Message findApplyList(@RequestBody Map<String,Object> data) {

		Object transFerType = data.get("transFerType");
		if (StringUtils.isBlank(transFerType)) {// 转出
			IPage<Object> selectPage = service.findApplyList(data);
			return Message.success("",selectPage.getRecords(),selectPage.getPages());
		}

		if ("1".equals(String.valueOf(transFerType))) {// 转入
			String type = String.valueOf(data.get("type"));
			if ("1".equals(type)) { // 使用申请
				Map<String, Object> map = intoList(String.valueOf(data.get("userId")), StringUtils.toInteger(data.get("page")), StringUtils.toInteger(data.get("size")), 0, "use_apply");
				return Message.success("查询正在运行的任务列表成功", map.get("records"), map.get("total"));
			} else { // 合同申请
				Map<String, Object> map = intoList(String.valueOf(data.get("userId")), StringUtils.toInteger(data.get("page")), StringUtils.toInteger(data.get("size")), 0, "contract_apply");
				return Message.success("查询正在运行的任务列表成功", map.get("records"), map.get("total"));
			}
		}
		return Message.success("查询正在运行的任务列表成功", null);
	}


	/**
	 *
	 * @author 苏小林
	 * @date 2020/7/1 16:25
	 * @param: data
	 * @return: com.xhsj.badges.utils.Message
	 */
	@ApiOperation(value = "查询证章模块审批待转入转出列表", notes = "查询证章模块审批待转入转出列表")
	@RequestMapping(value="/findApplyAuditList",method = RequestMethod.POST)
	public Message findApplyAuditList(@RequestBody Map<String,Object> data) {
		Object userId = data.get("userId");
		if (Objects.isNull(userId)) {
			return Message.error("userId不能为空");
		}

		Object transFerType = data.get("transFerType");
		if (StringUtils.isBlank(transFerType)) {// 转出
			IPage<Map<String, Object>> selectPage = service.findRunTaskList(data);
			for (Map<String, Object> record : selectPage.getRecords()) {
				Object processTaskId = record.get("processTaskId");
				Map<String, String> map = tbBadgesUseApplyMapper.getTransferByDataId(String.valueOf(processTaskId));
				if (map !=null) {
					List<Object> list = Lists.newArrayList();
					list.add(map.get("dept_id"));
					list.add(map.get("user_id"));
					record.put("userList",list);
					record.put("transferId",map.get("id"));
				}else{
					List<Object> list = Lists.newArrayList();
					record.put("userList",list);
					record.put("transferId","");
				}
			}
			return Message.success("",selectPage.getRecords(),selectPage.getTotal());
		}

		if ("1".equals(String.valueOf(transFerType))) {// 转入
			String type = String.valueOf(data.get("type"));
			if ("2".equals(type)) { // 合同审核
				Map<String, Object> map = intoList(String.valueOf(data.get("userId")), StringUtils.toInteger(data.get("page")), StringUtils.toInteger(data.get("size")), 1, "contract_audit");
				return Message.success("查询正在运行的任务列表成功", map.get("records"), map.get("total"));
			} else { // 使用审核
				Map<String, Object> map = intoList(String.valueOf(data.get("userId")), StringUtils.toInteger(data.get("page")), StringUtils.toInteger(data.get("size")), 1, "use_audit");
				return Message.success("查询正在运行的任务列表成功", map.get("records"), map.get("total"));
			}
		}
		return Message.success("查询正在运行的任务列表成功", null);

	}


	private Map<String, Object> intoList(String userId, Integer page, Integer size, int taskType, String applyType) {

		IPage<Object> iPage = new Page<>(page, size);
		IPage<Map<String,Object>> selectPage = tbBadgesUseApplyMapper.getTransferList(iPage,userId,1,taskType,0,applyType);
		Map<String, Object> result = Maps.newHashMap();
		if (selectPage != null) {
			List<Object> objects = Lists.newArrayList();
			List<Map<String, Object>> records = selectPage.getRecords();
			for (Map<String, Object> record : records) {
				Object content = record.get("content");
				JSONObject jsonObject = JSONObject.parseObject(content.toString());
				jsonObject.put("transferId", record.get("id"));
				objects.add(jsonObject);
			}
			System.err.println(objects);
			result.put("total", selectPage.getTotal());
			result.put("records", objects);
		}
		return result;
	}

	@ApiOperation(value = "通过id查询", notes = "通过id查询")
	@GetMapping("/getById")
	public Message getById(@RequestParam("id") String id) {
		try {
			TbBadgesUseApply tbBadgesUseApply = service.getById(id);
			String type = tbBadgesUseApply.getType();
			if (StringUtils.isNotBlank(type)) {
				List<String> list = Arrays.asList(type.split(","));
				tbBadgesUseApply.setTypes(list);
			}
			return Message.success("",tbBadgesUseApply);
		} catch (Exception e) {
			e.printStackTrace();
			return Message.error("查询异常");
		}


	}

	@ApiImplicitParam(name = "data", value = "{\n" +
			"\"page\":1,\n" +
			"\"size\":10,\n" +
			"\"userId\":\"277\",\n" +
			"\"status\":0\n" +
			"\"name\":0\n" +
			"}", required = true, dataType = "Map")
	@ApiOperation(value = "查询历史任务表所有数据list", notes = "查询历史任务表所有数据list。")
	@RequestMapping(value="/findHiTaskList",method = RequestMethod.POST)
	//@PreAuthorize("hasAuthority('tb:badges:process:task:view')")
	public Message findHiTaskList(@RequestBody Map<String,Object> data){

		if (Objects.isNull(data.get("userId"))) {
			return Message.error("userId不能为空");
		}
		IPage<Map<String,Object>> selectPage = service.findHiTaskList(data);

		return Message.success("",selectPage.getRecords(),selectPage.getTotal());
	}

	@ApiImplicitParam(name = "data", value = " {\n" +
			"\"page\":1,\n" +
			"\"size\":10,\n" +
			"\"userId\":\"277\"\n" +
			"}", required = true, dataType = "Map")
	@ApiOperation(value = "查询正在运行的任务列表", notes = "查询正在运行的任务列表")
	@RequestMapping(value="/findRunTaskList",method = RequestMethod.POST)
	public Message findRunTaskList(@RequestBody Map<String,Object> data) {
		try {

			Object userId = data.get("userId");
			if (Objects.isNull(userId)) {
//				return new Result<>(Result.CODE_FAILED,"userId不能为空");
				return Message.error("userId不能为空");
			}

			IPage<Map<String, Object>> selectPage = service.findRunTaskList(data);
//			return new Result<>(Result.CODE_SUCCESS,"",selectPage.getRecords(),selectPage.getTotal(),selectPage.getPages());
			return Message.success("",selectPage.getRecords(),selectPage.getTotal());
		} catch (Exception e) {
			e.printStackTrace();
//			return new Result<>(Result.CODE_FAILED,"查询异常",e.getMessage());
			return Message.error("查询异常");
		}
	}

	//获取审批意见
    @ApiImplicitParam(name = "data", value = " ", required = true, dataType = "Map")
    @ApiOperation(value = "获取审批意见", notes = "获取审批意见")
    @RequestMapping(value="/findAuditOpinionList",method = RequestMethod.POST)
    public Message findAuditOpinionList(@RequestBody Map<String,Object> data) {
        try {

            Object dataId = data.get("dataId");
            if (Objects.isNull(dataId)) {
				return Message.error("业务id不能为空");
            }
             List<Map<String,Object>> findAuditOpinionList= tbBadgesProcessOpinionService.findAuditOpinionList(String.valueOf(dataId));
			return Message.success("",findAuditOpinionList);
        } catch (Exception e) {
            e.printStackTrace();
			return Message.error("查询异常");
        }
    }

	/**
	 * 根据证章id查询使用记录
	 * @author 苏小林
	 * @date 2020/3/24 10:30
	 * @param: id
	 */
	@ApiOperation(value = "根据证章id查询使用记录", notes = "根据证章id查询使用记录")
	@RequestMapping(value="/findUserRecord",method = RequestMethod.POST)
    public Message findUserRecord(@RequestBody Map<String,Object> data){

		try {
//			QueryWrapper<TbBadgesUseApply> queryWrapper = new QueryWrapper<>();
//			queryWrapper.eq("badges_manager_id",id);
//			queryWrapper.eq("node_name","完结");
//			List<TbBadgesUseApply> list = service.list(queryWrapper);

			IPage<Map<String,Object>> page = service.findUserRecord(data);

//			return new Result<>(Result.CODE_SUCCESS,"",page.getRecords(),page.getTotal());
			return Message.success("",page.getRecords(),page.getTotal());
		} catch (Exception e) {
			e.printStackTrace();
			return Message.error("查询异常");
		}

	}

	@ApiOperation(value="证章或合同代办数",notes ="证章或合同代办数" )
	@GetMapping("/badgesAgencyNum")
	@ResponseBody
	public Message badgesAgencyNum(@RequestParam("userId") Integer userId,@RequestParam("type") Integer type){
		try {
			return Message.success("成功",service.badgesOrContractAgencyNum(userId,type));
		}catch (Exception e){
			log.error("信息:{}",e);
			e.printStackTrace();
			return Message.error(1,"失败");
		}
	}

   /**
       * @Description: 部门用章统计
       * @Param:  date-日期
       * @Author: liuqinghua
       * @Date: 2021/9/6 
       */
	@ApiOperation(value="部门用章统计",notes ="部门用章统计" )
	@GetMapping("/getBadgesStatistics")
	public Message getBadgesStatistics(@RequestParam String date){
		try {
			// 判断日期格式是否正确
			if(!Pattern.matches(DateUtils.MONTH_REGEX, date))
				return Message.error("日期格式不对，请按照yyyy-MM");
            List<Map<String, Integer>> badgesStatistics = service.getBadgesStatistics(date);
            int total = badgesStatistics.stream().mapToInt(e -> Integer.valueOf(String.valueOf(e.get("value")))).sum();
            return Message.success("成功",badgesStatistics,total);
		}catch (Exception e){
			log.error("信息:{}",e);
			e.printStackTrace();
			return Message.error(1,"失败");
		}
	}


}

